<template>
  <div class="search">
    <form action="/">
      <van-search background="#4fc08d" v-model="value" show-action
        placeholder="请输入搜索关键词" @search="onSearch" @focus="isResultShow=false"
        @cancel="onCancel" />
    </form>
    <!-- 搜索结果 -->
    <result v-if="isResultShow" :searchText='value'></result>
    <!-- 联想建议 -->
    <sugger v-else-if="value" :searchText='value'></sugger>
    <!-- 搜索历史 -->
    <history @addSearch='addSearch' v-else :history='history'></history>

  </div>
</template>

<script>
import history from './components/search-history.vue'
import result from './components/search-result.vue'
import sugger from './components/search-sugger.vue'
export default {
  data () {
    return {
      value: '',
      isResultShow: false
    }
  },
  methods: {
    onSearch (val) {
      this.history.unshift(val)
      // console.log(t);
      const set = new Set()
      this.history.forEach(val => set.add(val))
      this.history = Array.from(set)
      this.isResultShow = true
    },
    // 搜索框取消事件
    onCancel () {
      this.$router.back()
    },
    addSearch (val) {
      this.value = val
      this.onSearch(val)
      console.log(val)
    }
  },
  components: {
    history,
    result,
    sugger
  },
  computed: {
    history: {
      get () {
        return this.$store.state.userHistory || []
      },
      set (val) {
        this.$store.commit('setHistory', val)
      }

    }
  }
}
</script>

<style scoped lang="less">
</style>
